import { Injectable } from '@nestjs/common';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { InjectRepository } from '@nestjs/typeorm';

import { Repository } from 'typeorm';
import { Permission } from './entities/permission.entity';
import { responseData } from '../common/response.handle';
import { IPaginationOptions } from '../utils/types/pagination-options';
import { addChildrenToData } from 'src/utils/utils';

@Injectable()
export class PermissionService {
	constructor(
		@InjectRepository(Permission)
		private permissionRepository: Repository<Permission>,
	) {}

	async create(createPermissionDto: CreatePermissionDto, userId: string) {
		return this.permissionRepository.save(
			this.permissionRepository.create({
				...createPermissionDto,
				creatorId: userId,
			}),
		);
		return responseData(null, '创建权限成功');
	}

	async findAll() {
		const permissions = await this.permissionRepository.find();
		return responseData(
			permissions.filter((p: any) => p.parentId === null).map((p: any) => addChildrenToData(p, permissions as any)),
			'查询所有权限列表成功',
		);
	}

	// 分页查询
	async findListByPage(paginationOptions: IPaginationOptions) {
		// const [permissions, total] = await this.permissionRepository.findAndCount({
		//   skip: (paginationOptions.pageNum - 1) * paginationOptions.pageSize, // 起
		//   take: paginationOptions.pageSize,
		// });
		const [permissions, total] = await this.permissionRepository
			.createQueryBuilder('permissions')
			.leftJoinAndSelect('permissions.user', 'user')
			.where('name LIKE :name OR description LIKE :description OR resource LIKE :resource', {
				name: `%${paginationOptions.keyword}%`,
				description: `%${paginationOptions.keyword}%`,
				resource: `%${paginationOptions.keyword}%`,
			})
			.skip((paginationOptions.pageNum - 1) * paginationOptions.pageSize)
			.take(paginationOptions.pageSize)
			.getManyAndCount();
		return responseData(
			{
				list: permissions.map((item) => {
					const pms = item;
					const creator = pms.user.nickname;
					delete pms.user;
					return {
						...pms,
						creator,
					};
				}),
				total,
				totalPages: Math.ceil(total / paginationOptions.pageSize),
			},
			'查询权限列表成功',
		);
	}

	async findOne(id: number) {
		const permission = await this.permissionRepository.findOne({
			where: {
				id,
			},
		});
		return responseData(permission, '查询权限成功');
	}

	async update(id: number, updatePermissionDto: UpdatePermissionDto) {
		await this.permissionRepository.save(
			this.permissionRepository.create({
				id,
				...updatePermissionDto,
			}),
		);
		return responseData(null, '修改权限成功');
	}

	async remove(id: number) {
		await this.permissionRepository.delete(id);
		return responseData(null, '删除权限成功');
	}
}
